#include "docx2txt.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>

int main(int argc, char *argv[])
{
	/// 1. 检查命令行参数
	if (argc == 1)
	{
		printf("Usage: docx2txt file\n\n");
		return -1;
	}

	/// 2. 提取文件扩展名
	const char* oneFile = argv[1];
	const char* extFname = strrchr(oneFile, '.');
	if (extFname == NULL)
	{
		printf("Error: cannot get file extend name\n\n");
		return -2;
	}

	/// 3. 打开文件
	FILE* filePtr = fopen(oneFile, "rb");
	if (filePtr == NULL)
	{
		printf("Error: open file failed\n\n");
		return -3;
	}

	/// 4. 读取文件内容
	fseek(filePtr, 0L, SEEK_END);
	int fileSize = (int)ftell(filePtr);
	fseek(filePtr, 0L, SEEK_SET);
	char* fileBuf = new char[fileSize];
	fread(fileBuf, 1, fileSize, filePtr);
	fclose(filePtr);

	/// 5. 根据扩展名决定如何转换
	std::string txtResult = "";
	if (strcasecmp(extFname, ".docx") == 0)
	{
		printf("Mode: docx\n");
		txtResult = docx2txt(fileBuf, fileSize);
	}
	else if (strcasecmp(extFname, ".xlsx") == 0)
	{
		printf("Mode: xlsx\n");
		txtResult = xlsx2txt(fileBuf, fileSize);
	}
	else
	{
		printf("Error: Unknown Mode [%s]\n", extFname + 1);
		delete[] fileBuf;
		return -4;
	}
	
	/// 6. 将转换结果打印到屏幕上
	printf("Text Result:\n%s\n\n", txtResult.c_str());

	delete[] fileBuf;

	return EXIT_SUCCESS;
}

